package com.wuuxiang.i5xforyou;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

@Component
@Primary
public class AggregatedSwaggerResourcesProvider implements SwaggerResourcesProvider {

	@Autowired
	private DiscoveryClient discoveryClient;
	
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	@Override
	public List<SwaggerResource> get() {
		List<SwaggerResource> resources = new ArrayList<SwaggerResource>();
		List<String> services =  discoveryClient.getServices();
		if (!CollectionUtils.isEmpty(services)) {
			for (String serviceId : services) {
				if (!serviceId.startsWith("i5xforyou-dependency") && !serviceId.startsWith("i5xforyou-service")) {
					ServiceInstance selectedInstance = loadBalancerClient.choose(serviceId);
					if (selectedInstance != null) {
						String documentationUri = "/api-docs/" + serviceId;
						String contextPath = StringUtils.trimToEmpty(selectedInstance.getMetadata().get("context-path"));
                        if (StringUtils.isNotBlank(contextPath)) {
                            documentationUri += "?contextpath=" + contextPath;
                            resources.add(swaggerResource(serviceId, documentationUri, "1.0.0"));
                        }
					}
				}
			}
		}
		return resources;
	}

	private SwaggerResource swaggerResource(String name, String location, String version) {
		SwaggerResource swaggerResource = new SwaggerResource();
		swaggerResource.setName(name);
		swaggerResource.setLocation(location);
		swaggerResource.setSwaggerVersion(version);
		return swaggerResource;
	}

	
	/*extends WebMvcConfigurationSupport 
	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		// registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		super.addResourceHandlers(registry);
	}*/
	
}
